package com.ray.auth.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ray.auth.common.CommonValue;
import com.ray.auth.system.emun.OrgType;
import com.ray.auth.system.service.OrganizationService;
import com.ray.auth.system.service.UserService;
import com.ray.auth.system.table.entity.Organization;
import com.ray.auth.system.table.entity.OrganizationExample;
import com.ray.auth.system.table.entity.OrganizationExample.Criteria;
import com.ray.auth.system.table.entity.User;
import com.ray.auth.system.table.mapper.OrganizationMapper;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.zjhc.flyhong.common.datastructure.TreeNode;
import com.zjhc.flyhong.common.function.enums.DeleteEnum;
import com.zjhc.flyhong.common.function.exception.BussinessException;
import com.zjhc.flyhong.common.function.operator.LoginUser;
import com.zjhc.flyhong.common.function.operator.PageDto;
import com.zjhc.flyhong.common.util.UUIDUtil;
import com.zjhc.flyhong.common.web.ErrorMsg;
import com.zjhc.flyhong.common.web.Result;
import com.zjhc.flyhong.common.web.SuccessMsg;
import com.zjhc.flyhong.common.web.base.BaseService;

/**
 * <h1>系统权限应用  组织  服务实现</h1>
 * @创建人 ray
 * @创建时间 2017-06-15
 * @版本 1.0
 * @重要修改备注 
 * 
 */
@Service
public class OrganizationServiceImpl extends BaseService implements OrganizationService {
	/**日志对象**/
	private static Logger logger = Logger.getLogger(OrganizationServiceImpl.class);
	/***数据库的操作对象**/
	@Autowired
	private OrganizationMapper organizationMapper;
	/**用户服务**/
	@Autowired
	private UserService userService;
	/**
     * 通过租户ID获取 组织信息
     * @param tenantId 租户ID
     * @return 组织信息
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Organization queryOrgByTenantId(String tenantId) {
		//查询条件
		OrganizationExample example = new OrganizationExample();
		example.createCriteria().andOrgTypeEqualTo(OrgType.TENANT.getType())
		.andTenantIdEqualTo(tenantId).andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		//查询数据
		List<Organization> list = organizationMapper.selectByExample(example);
		if(ObjectUtil.isNull(list) || list.isEmpty()){
			logger.info("Organization list is empty.");
			return null;
		}
		//判断是否查询多了数据
		if(list.size() >1){
			throw new RuntimeException("two many record by query,RecordCount:"+list.size());
		}
		
		return list.get(0);
	}
	/**
     * 通过用户ID获取 组织信息
     * @param userId 用户ID
     * @return 组织信息
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Organization queryOrgByUser(String userId) {
		//查询用户所拥有的租户id
		User user = userService.queryUserByUserId(userId);
		if(ObjectUtil.isNull(user)){
			logger.info("user is empty.");
			return null;
		}
		String tenantId = "";
		return queryOrgByTenantId(tenantId);
	}
	/**
     * 通过组织ID获取 组织信息
     * @param orgCode 组织编号
     * @return 组织信息
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Organization queryOrgByOrgCode(String orgCode) {
		//查询条件
		OrganizationExample example = new OrganizationExample();
		example.createCriteria()//.andOrgTypeEqualTo(OrgType.TENANT.getType())
		.andOrgIdEqualTo(orgCode).andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		//查询数据
		List<Organization> list = organizationMapper.selectByExample(example);
		if(ObjectUtil.isNull(list) || list.isEmpty()){
			logger.info("Organization list is empty.");
			return null;
		}
		//判断是否查询多了数据
		if(list.size() >1){
			throw new RuntimeException("too many Organization by find.");
		}
		return list.get(0);
	}
	/**
	 * 查询所有租户
	 * @param params 查询参数
	 * @param page 分页信息
	 * @param loginUser 登录用户
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public PageDto<Organization> queryTenantList(Organization params, PageDto<Organization> page, LoginUser loginUser) {
		OrganizationExample example = new OrganizationExample();
		Criteria criteria =  example.createCriteria();
		//部门名称
		if(StrUtil.isNotBlank(params.getOrgName())){
			criteria.andOrgNameLike(params.getOrgName()+"%");
		}
		//部门联系电话
		if(StrUtil.isNotBlank(params.getOrgPhone())){
			criteria.andOrgPhoneLike(params.getOrgPhone()+"%");
		}
		//部门负责人联系电话
		if(StrUtil.isNotBlank(params.getOrgManagerPhone())){
			criteria.andOrgManagerPhoneLike(params.getOrgManagerPhone()+"%");
		}
		//部门地址
		if(StrUtil.isNotBlank(params.getOrgAddress())){
			criteria.andOrgAddressLike(params.getOrgAddress()+"%");
		}
		
		criteria.andOrgTypeEqualTo(OrgType.TENANT.getType())
		.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		this.setExamplePage(example, page);
		page.setTotal(organizationMapper.countByExample(example));
		page.setRecords(organizationMapper.selectByExample(example));
		return page;
	}
	
	/**
	 * 查询所有租户
	 * @param params 查询参数
	 * @param page 分页信息
	 * @param loginUser 登录用户
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public PageDto<Organization> queryOrgList(Organization params, PageDto<Organization> page, LoginUser loginUser) {
		OrganizationExample example = new OrganizationExample();
		Criteria criteria =  example.createCriteria();
		//不是超级管理员只能看到自己所属的机构
		if(!loginUser.isSuperManager()){
			criteria.andTenantIdEqualTo(loginUser.getTenantId());
		}
		//部门名称
		if(StrUtil.isNotBlank(params.getOrgName())){
			criteria.andOrgNameLike(params.getOrgName()+"%");
		}
		//部门联系电话
		if(StrUtil.isNotBlank(params.getOrgPhone())){
			criteria.andOrgPhoneLike(params.getOrgPhone()+"%");
		}
		//部门负责人联系电话
		if(StrUtil.isNotBlank(params.getOrgManagerPhone())){
			criteria.andOrgManagerPhoneLike(params.getOrgManagerPhone()+"%");
		}
		//部门地址
		if(StrUtil.isNotBlank(params.getOrgAddress())){
			criteria.andOrgAddressLike(params.getOrgAddress()+"%");
		}
		//根据上级查询
		if(StrUtil.isNotBlank(params.getParentOrgId())){
			criteria.andParentOrgIdEqualTo(params.getParentOrgId());
		}
		criteria.andOrgTypeEqualTo(OrgType.DEPT.getType())
		.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		this.setExamplePage(example, page);
		page.setTotal(organizationMapper.countByExample(example));
		page.setRecords(organizationMapper.selectByExample(example));
		return page;
	}
	/**
	 * 新增一个组织数据
	 * @param params 新增对象
	 * @param type 组织类型  租户或者部门
	 * @param loginUser 操作用户
	 * @return
	 */
	@Transactional
	public Result<Object> addOrganization(Organization params, String type, LoginUser loginUser) {
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		//所有租户的上级0
		if(StrUtil.equals(type, OrgType.TENANT.getType())){
			//params.setParentOrgId(CommonValue.treeTopId);
			//新增数据生成默认租户ID
			params.setTenantId(UUIDUtil.getUUID());
		}else{
			params.setTenantId(loginUser.getTenantId());
		}
		//设置部门类型
		params.setOrgType(type);
		params.setOrgId(UUIDUtil.getUUID());
		params.setIsDelete(DeleteEnum.USE.getValue());
		this.setUserForAdd(params, loginUser);
		int opCount = organizationMapper.insertSelective(params);
		if(opCount != 1){
			logger.error("OrganizationServiceImpl=>addOrganization is error");
			throw new BussinessException(-1, ErrorMsg.INSERT_ERROR);
		}
		return result;
	}
	/**
	 * 修改一个组织数据
	 * @param params 新增对象
	 * @param type 组织类型  租户或者部门
	 * @param loginUser 操作用户
	 * @return
	 */
	@Transactional
	public Result<Object> updateOrganization(Organization params, String type, LoginUser loginUser) {
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		this.setUserForUpdate(params, loginUser);
		//设置部门类型
		int opCount = organizationMapper.updateByPrimaryKeySelective(params);
		if(opCount != 1){
			logger.error("OrganizationServiceImpl=>updateOrganization is error");
			throw new BussinessException(-1, ErrorMsg.UPDATE_ERROR);
		}
		return result;
	}
	/**
	 * 通过主键删除数据
	 * @param id 主键
	 * @param loginUser 操作用户
	 * @return
	 */
	@Transactional
	public Result<Object> deleteOrganization(String id, LoginUser loginUser) {
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		Organization record = new Organization();
		record.setOrgId(id);
		record.setIsDelete(DeleteEnum.DELETE.getValue());
		this.setUserForUpdate(record, loginUser);
		int opCount = organizationMapper.updateByPrimaryKeySelective(record);
		if(opCount != 1){
			logger.error("OrganizationServiceImpl=>deleteOrganization is error");
			throw new BussinessException(-1, ErrorMsg.DELETE_ERROR);
		}
		return result;
	}
	/**
	 * 组织树
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<TreeNode> queryOrgListByParentId(String id, Integer level, LoginUser loginUser) {
		List<TreeNode> list = new ArrayList<TreeNode>();
		//超级管理员查看所有部门
		if(StrUtil.isBlank(id)){
		   id = CommonValue.treeTopId;
		}
		list.addAll(queryChildOrg(id,level,loginUser));
		return list;
	}
	
	/**
     * 查询当前id下的组织
     * @param id
     * @param loginUser
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	private List<TreeNode> queryChildOrg(String id, Integer level,LoginUser loginUser) {
		ArrayList<TreeNode> list = new ArrayList<TreeNode>();
		OrganizationExample example = new OrganizationExample();
		Criteria criteria = example.createCriteria();
		//不是超级管理员只能看到自己所属的机构
		if(!loginUser.isSuperManager()){
			criteria.andTenantIdEqualTo(loginUser.getTenantId());
		}
		criteria.andParentOrgIdEqualTo(id)
		.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		example.setOrderByClause("INDEX_SORT ASC");
		List<Organization> orgList = organizationMapper.selectByExample(example);
		TreeNode node = null;
		for(Organization org : orgList){
			node = new TreeNode(org.getOrgId(), org.getOrgName(),level, false);
			node.setValue(org);
			list.add(node);
		}
		return list;
	}
	
	/**
	 * 查询组织
	 * @param id
	 * @param user
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Organization queryOrg(String id, LoginUser user){
		return organizationMapper.selectByPrimaryKey(id);
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<Organization> queryAll(LoginUser user) {
		//查询条件
		OrganizationExample example = new OrganizationExample();
		Criteria criteria = example.createCriteria();
		if(!user.isSuperManager()){
			criteria.andTenantIdEqualTo(user.getTenantId());
		}
		criteria.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		//查询数据
		return  organizationMapper.selectByExample(example);
	}
}
